﻿using UnityEngine;
using TinyWnd;

public enum MsgBoxType
{
    ok,
    okCancel,
}

public class MsgBoxContent : WndContentData
{
    public MsgBoxType boxType;
    public string text;
    public System.Action cbOk;
    public System.Action cbCancel;
}

public class MsgBoxWnd : Wnd
{
    TweenScale twScale;
    UILabel label;
    UIGrid grid;
    GameObject goBtnOk;
    GameObject goBtnCancel;

    MsgBoxContent _content;

    protected override void OnAwake()
    {
        _wndId = WndId.msgBox;
        _colliderMode = WndColliderMode.opaque;
        _closeClickBg = true;
        _unifiedClose = true;

        var tran = transform;
        twScale = Utility.FindChild<TweenScale>(tran, "Center/Bg");
        label = Utility.FindChild<UILabel>(tran, "Center/Bg/Content");
        grid = Utility.FindChild<UIGrid>(tran, "Center/Bg/Btns");
        goBtnOk = Utility.FindChild(tran, "Center/Bg/Btns/BtnOk").gameObject;
        goBtnCancel = Utility.FindChild(tran, "Center/Bg/Btns/BtnCancel").gameObject;

        UIEventListener.Get(goBtnOk).onClick = delegate
        {
            ClickOk();
        };

        UIEventListener.Get(goBtnCancel).onClick = delegate
        {
            ClickCancel();
        };
    }

    protected override void OnShow(WndContentData content)
    {
        _content = content as MsgBoxContent;

        gameObject.SetActive(true);
        EventDelegate.Remove(twScale.onFinished, FinishCb);
        twScale.PlayForward();

        if (_content.boxType == MsgBoxType.ok)
        {
            goBtnOk.SetActive(true);
            goBtnCancel.SetActive(false);
        }
        else if (_content.boxType == MsgBoxType.okCancel)
        {
            goBtnOk.SetActive(true);
            goBtnCancel.SetActive(true);
        }
        label.text = _content.text;
        grid.repositionNow = true;
    }

    protected override void OnHide()
    {
        EventDelegate.Add(twScale.onFinished, FinishCb);
        twScale.PlayReverse();
    }

    void FinishCb()
    {
        gameObject.SetActive(false);
    }

    void ClickOk()
    {
        if (_content != null && _content.cbOk != null)
            _content.cbOk.Invoke();
        Close();
    }

    void ClickCancel()
    {
        if (_content != null && _content.cbCancel != null)
            _content.cbCancel.Invoke();
        Close();
    }
}
